<template>
  <div>
    <van-nav-bar
      title="商品详情"
      left-text="返回"
      right-text="按钮"
      left-arrow
      @click-left="handleBack"
      @click-right=""
    />
    <van-swipe :autoplay="3000" indicator-color="white">
      <van-swipe-item v-for="(item, index) in bannerList" :key="index">
        <img :src="item" alt="" />
      </van-swipe-item>
    </van-swipe>
    <h3>{{ query.proname }}</h3>
    <p>￥{{ query.originprice }}</p>
    <van-action-bar>
      <van-action-bar-icon icon="chat-o" text="客服" />
      <van-action-bar-icon
        icon="cart-o"
        text="购物车"
        :badge="cart.allInfo.allNum"
        @click="handleCart"
      />
      <van-action-bar-icon icon="shop-o" text="店铺" />
      <van-action-bar-button
        type="warning"
        text="加入购物车"
        @click="handleAdd"
      />
      <van-action-bar-button type="danger" text="立即购买" />
    </van-action-bar>
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <div class="good-list">
        <GoodItem v-for="item in list" :gdata="item" />
      </div>
    </van-list>
  </div>
</template>

<script setup lang="ts">
import { showToast } from "vant";
import { ref, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useCart } from "../store/cart";
import { useUserStore } from "../store/user";
import { ProductType } from "../types/prod";
import { useGoodsList } from "../hook/list";
const { list, finished, loading, onLoad } = useGoodsList(); //调用自定义Hook
const router = useRouter();
const { query } = useRoute();
const userStore = useUserStore();
const handleBack = () => {
  router.go(-1);
};

// 从路由数据包中提取img1~img4,存入一个独立computed数组
const bannerList = computed<Array<string>>(() => {
  let arr = [];
  for (let attr in query) {
    if (attr.indexOf("img") != -1) {
      arr.push(query[attr] as string);
    }
  }
  return arr;
});
// 购物车
const cart = useCart();
const handleAdd = () => {
  if (userStore.userInfo) {
    cart.cartAddAction(
      query as unknown as ProductType,
      userStore.userInfo.objectId
    );
  } else {
    router.push("/login");
  }
};

const handleCart = () => {
  router.push("/cart");
};
</script>

<style scoped></style>
